#!/bin/bash

set -e
set -o pipefail

handle_error() {
    local exit_code=$?
    echo "Error occurred in script at line: ${1} with exit code: ${exit_code}"
    exit $exit_code
}

trap 'handle_error ${LINENO}' ERR

GIT_USER=$1
GIT_TOKEN=$2
CONAN_USER=$3
CONAN_PASSWORD=$4
GITCODE_DOMAIN=$5

cur_path=$(pwd)

echo "===start to publish component==="
chmod +x scripts/common_scripts/common.sh
source scripts/common_scripts/common.sh

function work() {
  cd ${cur_path}

  echo "1. prepare env"
  pip3 install -r ${cur_path}/scripts/publish_pipeline/publish_by_comment/requirements.txt
  mkdir ~/repo/
  cd ~/repo/
  ret=$(python3 ${cur_path}/scripts/utils/prepare-env.py --gitcode_domain="${GITCODE_DOMAIN}")
  package=$(echo ${ret} | jq -r '.package')

  echo "2.prepare the env about docker..."
  repo_name=$(echo ${package} | rev | cut -d/ -f1 | rev | cut -d. -f1)
  cd ~/repo/${repo_name}
  json_file="mds/service.json"
  name=$(jq -r '.name' "$json_file")
  version=$(jq -r '.version' "$json_file")
  package_name="$name/$version"

  build_component ~/repo/${repo_name}
  upload_conan ~/repo/${repo_name} ${package_name}
}

function prepare_sdk() {
  cd ~
  git clone https://gitcode.com/openUBMC/manifest.git
  cd ~/manifest
  bingo build -t install_sdk || true
}

function main() {
  prepare_software
  prepare_git ${GIT_USER} ${GIT_TOKEN}
  prepare_conan2 ${CONAN_USER} ${CONAN_PASSWORD}
  prepare_bingo
  prepare_sdk
  work
}

main

exit 0
